// API基础URL
const API_BASE_URL = '/api';

// 工具函数：获取带过期时间的本地存储项
function getItemWithExpiry(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) {
        return null;
    }
    const item = JSON.parse(itemStr);
    const now = new Date();
    if (now.getTime() > item.expiry) {
        localStorage.removeItem(key);
        return null;
    }
    return item.value;
}

// 工具函数：设置带过期时间的本地存储项
function setItemWithExpiry(key, value, ttl) {
    const now = new Date();
    const item = {
        value: value,
        expiry: now.getTime() + ttl,
    };
    localStorage.setItem(key, JSON.stringify(item));
}

// 获取用户ID
const userId = getItemWithExpiry('userId');

// 当前页码
let currentPage = 1;

// API请求函数
async function fetchAPI(endpoint, options = {}) {
    try {
        const response = await fetch(`http://localhost:8080${API_BASE_URL}${endpoint}`, {
            method: options.method || 'GET',  // 使用传入的method，默认为GET
            headers: {
                'Content-Type': 'application/json',
                'userId': userId,
                ...options.headers
            },
            body: options.body ? JSON.stringify(options.body) : undefined  // 如果有body则添加
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}

// 获取订单列表
async function getOrders(status = 'all', type = 'route', page = 1, pageSize = 5) {
    try {
        const params = new URLSearchParams({
            current: page,
            size: pageSize,
            ...(status !== 'all' && { status })
        });
        
        // 根据type选择不同的API路径
        let endpoint = '';
        if (type === 'activity') {
            endpoint = '/orders/activity';
        } else if (type === 'route') {
            endpoint = '/orders/route';
        }
        
        if (!endpoint) {
            throw new Error('无效的订单类型');
        }
        
        const response = await fetchAPI(`${endpoint}?${params}`);
        return response;
    } catch (error) {
        console.error('获取订单列表失败:', error);
        return { code: 500, message: '获取订单列表失败', data: { records: [], total: 0 } };
    }
}

// 搜索订单
async function searchOrders(keyword, type, page = 1, pageSize = 5) {
    try {
        let endpoint = '';
        const params = new URLSearchParams({
            current: page,
            size: pageSize,
            keyword: keyword
        });
        
        if (type === 'activity') {
            endpoint = `/orders/search?${params}`;
        } else if (type === 'route') {
            endpoint = `/orders/route/search?${params}`;
        }
        
        if (!endpoint) {
            throw new Error('无效的订单类型');
        }
        
        console.log('搜索请求URL:', endpoint);
        const data = await fetchAPI(endpoint);
        console.log('搜索响应数据:', data);
        return data;
    } catch (error) {
        console.error('搜索订单失败:', error);
        return { orders: [] };
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查用户是否登录
    if (!userId) {
        window.location.href = '/login.html';
        return;
    }
    
    initOrderFilters();
    initSearchBox();
    // 默认加载旅游线路订单
    loadOrders('all', 'route');
    updatePagination(0); // 初始化为0，等待数据加载后更新
});

// 初始化订单筛选
function initOrderFilters() {
    const typeBtns = document.querySelectorAll('.filter-section:first-child .filter-btn');
    const statusBtns = document.querySelectorAll('.ticket-status .filter-btn');
    const ticketStatusSection = document.querySelector('.ticket-status');
    const searchInput = document.querySelector('.search-box input');
    
    // 类型筛选按钮事件
    typeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            typeBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentPage = 1;
            
            const type = btn.dataset.type;
            
            // 清空搜索栏
            searchInput.value = '';
            
            // 显示/隐藏状态筛选
            if (type === 'activity') {
                ticketStatusSection.style.display = 'flex';
                // 重置状态筛选为全部
                statusBtns.forEach(b => b.classList.remove('active'));
                statusBtns[0].classList.add('active');
                loadOrders('all', type);
            } else if (type === 'route') {
                ticketStatusSection.style.display = 'none';
                loadOrders('all', type);
            }
        });
    });
    
    // 状态筛选按钮事件（仅适用于汉文化活动）
    statusBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            statusBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentPage = 1;
            
            const status = btn.dataset.status;
            const type = document.querySelector('.filter-section:first-child .filter-btn.active').dataset.type;
            
            if (type === 'activity') {
                loadOrders(status, type);
            }
        });
    });
}

// 初始化搜索框
function initSearchBox() {
    const searchForm = document.querySelector('.search-box');
    const searchInput = searchForm.querySelector('input');
    
    searchForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const keyword = searchInput.value.trim();
        if (keyword) {
            await handleSearch(keyword);
        }
    });
}

// 处理搜索
async function handleSearch(keyword) {
    try {
        // 获取当前选中的订单类型
        const currentType = document.querySelector('.filter-section:first-child .filter-btn.active').dataset.type;
        console.log('当前搜索类型:', currentType);
        console.log('搜索关键词:', keyword);
        
        // 重置页码为1
        currentPage = 1;
        
        const response = await searchOrders(keyword, currentType, currentPage);
        const orderList = document.querySelector('.order-list');
        
        // 检查响应格式
        if (!response || response.code !== 200 || !response.data || !response.data.records) {
            console.error('搜索返回数据格式错误:', response);
            orderList.innerHTML = '<div class="no-orders">未找到相关订单</div>';
            updatePagination(0);
            return;
        }
        
        const orders = response.data.records;
        console.log('搜索结果数量:', orders.length);
        
        if (orders.length === 0) {
            orderList.innerHTML = '<div class="no-orders">未找到相关订单</div>';
            updatePagination(0);
            return;
        }
        
        // 显示搜索结果
        orderList.innerHTML = orders.map(order => createOrderItem(order)).join('');
        
        // 更新分页信息
        const total = response.data.total || 0;
        console.log('搜索结果总数:', total);
        updatePagination(total);
    } catch (error) {
        console.error('搜索失败:', error);
        const orderList = document.querySelector('.order-list');
        orderList.innerHTML = '<div class="error-message">搜索失败，请稍后重试</div>';
        updatePagination(0);
    }
}

// 获取线路图片
function getRouteImage(route) {
    const imageMap = {
        'culture': 'images/route1.jpg',
        'nature': 'images/route2.jpg'
    };
    return imageMap[route] || 'images/default.jpg';
}

// 获取线路名称
function getRouteName(route) {
    const nameMap = {
        'culture': '三国文化之旅',
        'nature': '山水风光之旅'
    };
    return nameMap[route] || '未知线路';
}

// 获取线路详情
function getRouteDetails(route) {
    const detailsMap = {
        'culture': {
            duration: '3天2晚',
            spots: '古汉台、武侯祠、张良庙、石门栈道',
            price: '¥899起'
        },
        'nature': {
            duration: '4天3晚',
            spots: '黎坪森林公园、华阳古镇、朱鹮保护区、龙头山',
            price: '¥1299起'
        }
    };
    return detailsMap[route] || { duration: '未知', spots: '未知', price: '未知' };
}

// 创建订单项HTML
function createOrderItem(order) {
    // 根据订单数据判断类型
    const orderType = order.activity ? 'activity' : 'route';
    console.log('订单类型:', orderType);
    console.log('活动/路线:', orderType === 'activity' ? order.activity : order.route);
    
    const statusClass = {
        'pending': 'status-pending',
        'certain': 'status-certain',
        'refund': 'status-refund',
        'expire': 'status-expire'
    };

    const statusText = {
        'pending': '待使用',
        'certain': '已完成',
        'refund': '退款中',
        'expire': '已过期'
    };

    const actionButtons = getActionButtons(order);
    
    // 根据订单类型生成不同的内容
    let orderContent = '';
    if (orderType === 'route') {
        const routeDetails = getRouteDetails(order.route);
        const imagePath = getRouteImage(order.route);
        console.log('路线图片路径:', imagePath);
        
        orderContent = `
            <div class="order-image" style="width: 200px; height: 150px; overflow: hidden; position: relative;">
                <img src="${imagePath}" 
                     alt="${getRouteName(order.route)}" 
                     style="width: 100%; height: 100%; object-fit: cover;"
                     onerror="this.onerror=null; this.src='images/default.jpg';">
            </div>
            <div class="order-info">
                <h3 class="order-title">${getRouteName(order.route)}</h3>
                <p class="order-details">行程天数：${routeDetails.duration}</p>
                <p class="order-details">景点：${routeDetails.spots}</p>
                <p class="order-details">价格：${routeDetails.price}</p>
                <p class="order-details">出行日期：${formatDate(order.date)}</p>
                <p class="order-details">出行人数：${order.people || 1}人</p>
                <p class="order-details">联系人：${order.username || '未知'}</p>
                <p class="order-details">联系电话：${order.phone || '未知'}</p>
            </div>
        `;
    } else if (orderType === 'activity') {
        const imagePath = getActivityImage(order.activity);
        console.log('活动图片路径:', imagePath);
        
        orderContent = `
            <div class="order-image" style="width: 200px; height: 150px; overflow: hidden; position: relative;">
                <img src="${imagePath}" 
                     alt="${getActivityName(order.activity)}" 
                     style="width: 100%; height: 100%; object-fit: cover;"
                     onerror="this.onerror=null; this.src='images/default.jpg';">
            </div>
            <div class="order-info">
                <h3 class="order-title">${getActivityName(order.activity)}</h3>
                <p class="order-details">用户名：${order.username || '未知'}</p>
                <p class="order-details">联系电话：${order.phone || '未知'}</p>
                <p class="order-details">邮箱：${order.email || '未知'}</p>
                <p class="order-details">活动日期：${formatDate(order.date)}</p>
                <p class="order-details">下单时间：${formatDate(order.createTime)}</p>
            </div>
        `;
    }
    
    // 根据订单类型决定是否显示状态
    const statusHtml = orderType === 'activity' ? 
        `<span class="order-status ${statusClass[order.status] || 'status-unknown'}">${statusText[order.status] || '未知状态'}</span>` : '';
    
    return `
        <div class="order-item">
            <div class="order-header">
                <span class="order-number">订单号：${order.id}</span>
                ${statusHtml}
            </div>
            <div class="order-content" style="display: flex; gap: 20px; padding: 15px;">
                ${orderContent}
            </div>
            <div class="order-footer">
                ${actionButtons}
            </div>
        </div>
    `;
}

// 根据订单状态获取操作按钮
function getActionButtons(order) {
    switch (order.status) {
        case 'pending':
            return `
                <button class="order-btn btn-primary" onclick="viewTicket('${order.id}')">查看门票</button>
                <button class="order-btn btn-secondary" onclick="applyRefund('${order.id}')">申请退款</button>
            `;
        case 'certain':
            return `
                <button class="order-btn btn-secondary" onclick="writeReview('${order.id}')">写评价</button>
            `;
        case 'refund':
            return `
                <button class="order-btn btn-secondary" disabled>退款处理中</button>
            `;
        case 'expire':
            return `
                <button class="order-btn btn-secondary" disabled>已过期</button>
            `;
        default:
            return '';
    }
}

// 查看门票
async function viewTicket(orderId) {
    try {
        // 创建模态框
        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;

        // 创建内容容器
        const content = document.createElement('div');
        content.style.cssText = `
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            position: relative;
        `;

        // 添加关闭按钮
        const closeBtn = document.createElement('button');
        closeBtn.textContent = '×';
        closeBtn.style.cssText = `
            position: absolute;
            right: 10px;
            top: 10px;
            border: none;
            background: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
        `;
        closeBtn.onclick = () => document.body.removeChild(modal);

        // 添加二维码图片
        const qrCode = document.createElement('img');
        qrCode.src = 'images/qrcode.png';
        qrCode.style.cssText = `
            max-width: 300px;
            margin: 20px 0;
        `;

        // 添加提示文字
        const text = document.createElement('p');
        text.textContent = '请出示此二维码给工作人员扫描';
        text.style.cssText = `
            margin: 10px 0;
            color: #333;
        `;

        // 组装模态框
        content.appendChild(closeBtn);
        content.appendChild(qrCode);
        content.appendChild(text);
        modal.appendChild(content);
        document.body.appendChild(modal);

        // 点击模态框背景关闭
        modal.onclick = (e) => {
            if (e.target === modal) {
                document.body.removeChild(modal);
            }
        };
    } catch (error) {
        console.error('显示门票失败:', error);
        alert('显示门票失败，请稍后重试');
    }
}

// 申请退款（后端让status显示"refund"）
async function applyRefund(orderId) {
    if (confirm('确定要申请退款吗？')) {
        try {
            const response = await fetchAPI(`/orders/${orderId}/refund`, {
                method: 'PUT'  // 改为PUT方法
            });
            
            if (response.code === 200) {
                alert('退款申请已提交');
                // 刷新当前页面的订单列表
                const status = document.querySelector('.filter-btn.active').dataset.status;
                await loadOrders(status);
            } else {
                alert('申请退款失败，请稍后重试');
            }
        } catch (error) {
            console.error('申请退款失败:', error);
            alert('申请退款失败，请稍后重试');
        }
    }
}

// 写评价
async function writeReview(orderId) {
    try {
        const response = await fetchAPI(`/orders/${orderId}/review`);
        if (response.code === 200 && response.data) {
            // 假设后端返回的是评价页面的URL
            window.location.href = response.data.reviewUrl;
        } else {
            alert('获取评价页面失败，请稍后重试');
        }
    } catch (error) {
        console.error('获取评价页面失败:', error);
        alert('获取评价页面失败，请稍后重试');
    }
}

// 获取活动类型的中文名称
function getActivityName(activity) {
    const activityMap = {
        'hanfu': '汉服体验',
        'calligraphy': '书法体验',
        'tea': '茶艺体验',
        'food': '美食制作'
    };
    return activityMap[activity] || activity || '未知活动';
}

// 获取活动图片
function getActivityImage(activity) {
    const imageMap = {
        'hanfu': 'images/culture1.jpg',
        'calligraphy': 'images/culture2.jpg',
        'tea': 'images/culture3.jpg',
        'food': 'images/culture4.jpg'
    };
    return imageMap[activity] || 'images/default.jpg';
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '未知';
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 更新分页
function updatePagination(total) {
    const pageSize = 5;
    const totalPages = Math.ceil(total / pageSize);
    const pagination = document.querySelector('.pagination');
    
    let paginationHTML = `
        <button class="page-btn" id="prevPage" ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fa fa-chevron-left"></i>
        </button>
        <div class="page-numbers">
    `;
    
    // 显示最多5个页码按钮
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <button class="page-btn ${i === currentPage ? 'active' : ''}" data-page="${i}">
                ${i}
            </button>
        `;
    }
    
    paginationHTML += `
        </div>
        <button class="page-btn" id="nextPage" ${currentPage === totalPages ? 'disabled' : ''}>
            <i class="fa fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = paginationHTML;
    
    // 添加分页事件监听
    const pageBtns = pagination.querySelectorAll('.page-btn');
    pageBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            if (btn.id === 'prevPage') {
                changePage(currentPage - 1);
            } else if (btn.id === 'nextPage') {
                changePage(currentPage + 1);
            } else {
                changePage(parseInt(btn.dataset.page));
            }
        });
    });
}

// 切换页码
async function changePage(page) {
    const type = document.querySelector('.filter-section:first-child .filter-btn.active').dataset.type;
    let status = 'all';
    
    if (type === 'activity') {
        status = document.querySelector('.ticket-status .filter-btn.active').dataset.status;
    }
    
    currentPage = page;
    
    // 检查是否有搜索关键词
    const searchInput = document.querySelector('.search-box input');
    const keyword = searchInput.value.trim();
    
    if (keyword) {
        // 如果有搜索关键词，使用搜索API
        await handleSearch(keyword);
    } else {
        // 如果没有搜索关键词，使用普通列表API
        await loadOrders(status, type);
    }
}

// 加载订单列表
async function loadOrders(status = 'all', type = 'route') {
    try {
        const pageSize = 5;
        const response = await getOrders(status, type, currentPage, pageSize);
        const orderList = document.querySelector('.order-list');
        
        if (!response || response.code !== 200 || !response.data || !response.data.records) {
            console.error('返回数据格式错误:', response);
            orderList.innerHTML = '<div class="no-orders">暂无订单数据</div>';
            updatePagination(0);
            return;
        }
        
        const orders = response.data.records;
        if (orders.length === 0) {
            orderList.innerHTML = '<div class="no-orders">暂无订单</div>';
            updatePagination(0);
            return;
        }
        
        orderList.innerHTML = orders.map(order => createOrderItem(order)).join('');
        
        const total = response.data.total || 0;
        updatePagination(total);
    } catch (error) {
        console.error('加载订单失败:', error);
        const orderList = document.querySelector('.order-list');
        orderList.innerHTML = '<div class="error-message">加载订单失败，请稍后重试</div>';
        updatePagination(0);
    }
}

// 添加样式
const style = document.createElement('style');
style.textContent = `
    .status-refund {
        background-color: #e74c3c;
        color: white;
    }
    
    .status-expire {
        background-color: #95a5a6;
        color: white;
    }
    
    .order-btn:disabled {
        background-color: #95a5a6;
        cursor: not-allowed;
        opacity: 0.7;
    }
`;
document.head.appendChild(style);